package com.longrise.android.byjk.utils;

import android.graphics.Bitmap;
import android.util.LruCache;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by sujizhong on 16/8/4.
 */
public class BitLruCache {

    private static BitLruCache mBitLruCache;

    private LruCache<String, Bitmap> mLruCache;

    private Lock mLock;

    private BitLruCache() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;
        mLruCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
        mLock = new ReentrantLock();
    }

    public static BitLruCache getInstance() {
        if (mBitLruCache == null) {
            synchronized (BitLruCache.class) {
                if (mBitLruCache == null) {
                    mBitLruCache = new BitLruCache();
                }
            }
        }
        return mBitLruCache;
    }

    public void addBitmapToLruCache(String key, Bitmap bitmap) {
        if (getBitmFromLruCache(key) == null) {
            if (bitmap != null) {
                mLruCache.put(key, bitmap);
            }
        }
    }

    public Bitmap getBitmFromLruCache(String key) {
        try {
            mLock.lock();
            Bitmap memoryBitmap = mLruCache.get(key);
            if (memoryBitmap != null) {
                return memoryBitmap;
            }
            return getDiskLruCache(key);
        } finally {
            mLock.unlock();
        }
    }

    private Bitmap getDiskLruCache(String key) {
        return null;
    }
}
